using LitJson;
namespace CGF
{
    public partial class PanelEditEmail : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        public static void Open()
        {
            UIManagerComponent.instance.OpenUI<PanelEditEmail>(UILayer.Normal, RootComponent.instance, true);
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelEditEmail>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelEditEmail", layer, isFloat);
			BindProperties(transform);
            
            BtnClose.SetClick(Close);

            InputField.text = UserInfo.Info["email"].ToString();
            
            BtnSendCode.SetClick(async () =>
            {
                if (!StringHelper.IsEmail(InputField.text))
                {
                    CGF.Dialog.Alert(I18N_email_invalid);
                    return;
                }
                JsonData data = new JsonData();
                data["email"] = InputField.text;
                Network.Res res = await Network.Post("/v1/reward/oauth/code/mail", data);
                if (res.success)
                {
                    CGF.Dialog.Alert(CommAssets.instance.I18N_sent_success);
                    BtnSendCode.GetComponent<BtnSendCode>().StartTimer();
                }
            });

            BtnConfirm.SetClick(async () =>
            {
                if (!StringHelper.IsEmail(InputField.text))
                {
                    CGF.Dialog.Alert(I18N_email_invalid);
                    return;
                }

                if (string.IsNullOrEmpty(InputCode.text))
                {
                    CGF.Dialog.Alert(I18N_please_input_code);
                    return;
                }
                JsonData data = new JsonData();
                data["email"] = InputField.text;
                data["code"] = InputCode.text;
                var res = await Network.Post("/v1/reward/oauth/bind/mail", data);
                if (res.success)
                {
                    JsonData info = UserInfo.Info;
                    info["email"] = InputField.text;
                    UserInfo.Info = info;
                    EventManager.Emit(new Event_UserInfoUpdate());
                    CGF.Dialog.Alert(I18N_edit_success, Close);
                }
            });
            
            ScaleIn(Dialog.transform);
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

    }
}
